//
//  AWOAuthController.swift
//  WeiBo
//
//  Created by AaronWei on 2017/6/5.
//  Copyright © 2017年 AaronWei. All rights reserved.
//

import UIKit
import SVProgressHUD

let AppKey = "1281857657"

let AppSecret = "e128a4acb250394801215dbb5af71262"

let Redirect_Uri = "http://www.itheima.com"

class AWOAuthController: UIViewController {
    
    private lazy var webView: UIWebView = UIWebView()
    
    
    override func loadView() {
        
        view = webView
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        loadRequest()
        
        view.backgroundColor = UIColor.white
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        
        if SVProgressHUD.isVisible() {
            
            SVProgressHUD.dismiss()
            
        }
        
    }
    
    private func loadRequest() {
        
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_Uri)"
        
        var urlRequest = URLRequest(url: URL(string: urlStr)!)
        
        urlRequest.timeoutInterval = 5.0
        
        webView.loadRequest(urlRequest)
        
    }
    
    private func setupUI() {
        
        webView.delegate = self
        
        navigationItem.title = "微博登录"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelButtonDidClicked))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillButtonDidClicked))
        
    }
    
    @objc private func cancelButtonDidClicked() {
        
        dismiss(animated: true, completion: nil)
        
    }
    
    @objc private func autoFillButtonDidClicked() {
        
        let jsString = "document.getElementById('userId').value = '297311774@qq.com', document.getElementById('passwd').value = 'wangwei920425..'"
        
        webView.stringByEvaluatingJavaScript(from: jsString)
        
    }
    
//    func requestAccessToken(code: String) {
//        
//        AWNetworkTools.sharedTools.requestAccessToken(code: code) { (response, error) in
//            
//            if error != nil {
//                
//                print(error!)
//                
//            } else {
//                
//                let dict = response as! [String: Any]
//                
//                let userAccount = AWUserAccountModel(dict: dict)
//                
//                self.requestUserInfo(userAccount: userAccount)
//                
//            }
//            
//        }
//        
//    }
//    
//    func requestUserInfo(userAccount: AWUserAccountModel) {
//        
//        AWNetworkTools.sharedTools.requestUserInfo(token: userAccount.access_token!, uid: userAccount.uid) { (response, error) in
//            
//            if error != nil {
//                
//                print("网络请求异常: \(error!)")
//                
//            } else {
//                
//                let dic = response as! [String: Any]
//                
//                let name = dic["name"] as? String
//                
//                let avatar_large = dic["avatar_large"] as? String
//                
//                userAccount.name = name
//                
//                userAccount.avatar_large = avatar_large
//                
//                userAccount.saveUserAccount()
//                
//            }
//            
//        }
//    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension AWOAuthController: UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
                
        if (request.url?.absoluteString.hasPrefix(Redirect_Uri))! {
            
            if let query = request.url?.query, query.hasPrefix("code=") {
                
                let code = query.substring(from: "code=".endIndex)
                
//                requestAccessToken(code: code)
                
                AWUserAccountViewModel.sharedViewModel.requestAccessToken(code: code, callBack: { (isLogin) in
                    
                    if isLogin {
                        
                        self.dismiss(animated: false, completion: { 
                            
                            NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotificationName), object: self)
                            
                        })
                        
                    } else {
                        
                        SVProgressHUD.setMinimumDismissTimeInterval(2.0)
                        
                        SVProgressHUD.showError(withStatus: "登录失败")
                        
                    }
                    
                })
                
            } else {
                
                dismiss(animated: true, completion: nil)
                
            }
            
            return false
            
        }
        
        return true
        
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
        
    }
    
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
        if error.localizedDescription == "The request timed out." {
            
            SVProgressHUD.setMinimumDismissTimeInterval(2.0)

            SVProgressHUD.showError(withStatus: "网络连接失败")
            
        } else {
            
            SVProgressHUD.dismiss()
            
        }
        
    }
    
}
